package com.ninelock.config.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ninelock.sso.entity.SysUser;
import com.ninelock.sso.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;


/**
 * @ClassName UserService @Description 登录逻辑
 *
 * @author gongym
 * @date 2018年10月30日 上午12:03:05
 */
@Component
public class UserService implements UserDetailsService {

  @Autowired
  private SysUserService sysUserService;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    QueryWrapper<SysUser> userWrapper = new QueryWrapper<>();
    userWrapper.eq("phone", username);
    SysUser sysUser = sysUserService.getOne(userWrapper);
    if (null != sysUser) {
      // 获取用户密码，如果密码不匹配会登录失败
      return new User(
          username,
          sysUser.getPassword(),
          AuthorityUtils.commaSeparatedStringToAuthorityList("USER_AUTHORITY"));
    } else {
      return null;
    }
  }
}
